package io.github.heollhai.common.utils;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @Author: lmf
 * @Create: 2024/8/5 13:28
 * Description:
 */
@Slf4j
public class ResponseUtils {
    /**
     * 向浏览器写入json数据
     */
    public static void writeJson(HttpServletResponse response, Object obj) {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try (PrintWriter pw = response.getWriter()){
            pw.print(JSON.toJSONString(obj));
            pw.flush();
        }catch (IOException e){
            log.error("写入前端异常: {}", e.getMessage());
        }
    }
}
